package testmutex

import "sync"

// Counter 抽象出读写操作的公共接口
type Counter interface {
	Read() int
	Increment()
}

// MutexCounter 使用 sync.Mutex 提供读/写串行化保护
type MutexCounter struct {
	mu    sync.Mutex
	value int
}

func (c *MutexCounter) Read() int {
	c.mu.Lock()
	v := c.value
	c.mu.Unlock()
	return v
}

func (c *MutexCounter) Increment() {
	c.mu.Lock()
	c.value++
	c.mu.Unlock()
}

// RWMutexCounter 使用 sync.RWMutex 允许并发读、互斥写
type RWMutexCounter struct {
	mu    sync.RWMutex
	value int
}

func (c *RWMutexCounter) Read() int {
	c.mu.RLock()
	v := c.value
	c.mu.RUnlock()
	return v
}

func (c *RWMutexCounter) Increment() {
	c.mu.Lock()
	c.value++
	c.mu.Unlock()
}
